package cn.parus.dynamicRouter.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @Title: JwtUtils
 * @Author 潘春兰
 * @Package cn.parus.auth.utils
 * @Date 2025/3/23 11:49
 * @description: TODO 使用jwt对token进行加密和解密
 * @Version:
 */
@Component
public class JwtUtils {

    @Value("${mini-gateway.JWT.EXPIRE_TIME}")
    private Long EXPIRE_TIME;// 过期时间 1个 小时

    @Value("${mini-gateway.JWT.SECRET_KEY}")
    private String SECRET_KEY;

    public Logger logger = Logger.getLogger(JwtUtils.class.getName());

    /**
     * 生成加密后的秘钥
     */
    private SecretKey generalKey() {
        return Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 生成JWT令牌
     */
    public String createJWT(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        return Jwts.builder()
                .setClaims(claims) // 自定义加密内容
                .setExpiration(expirationDate) // 过期时间
                .signWith(generalKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 解析JWT令牌
     */
    public Claims parseJWT(String token) {
        return Jwts.parser()
                .setSigningKey(generalKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }


    /**
     * 验证令牌是否有效且未过期
     */
    public boolean isNotExpired(String token) {
        if (token == null || token.isEmpty()) {
            logger.warning("Token不能为空");
            return false;
        }

        try {
            Jws<Claims> claimsJws = Jwts.parser()
                    .setSigningKey(generalKey())
                    .build()
                    .parseClaimsJws(token);

            Date expiration = claimsJws.getBody().getExpiration();
            boolean isValid = !expiration.before(new Date());
            if (isValid) {
                logger.info("令牌有效");
            }
            return isValid;
        } catch (ExpiredJwtException ex) {
            logger.info("令牌已过期");
            return false;
        } catch (JwtException | IllegalArgumentException ex) {
            logger.warning("无效的令牌: " + ex.getMessage());
            return false;
        }
    }
}


